package com.lew.scott.date;

import java.util.Date;

public class Solar2Lunar {

	public static LunarDate convertDate2LunarDate(Date objDate) {

		int i, leap = 0, temp = 0;
		int offset = (int) ((Date.UTC(objDate.getYear(), objDate.getMonth(), objDate.getDate(), 0, 0, 0) - Date.UTC(
				0, 0, 31, 0, 0, 0)) / 86400000);

		for (i = 1900; i < 2050 && offset > 0; i++) {
			temp = CalendarData.lYearDays(i);
			offset -= temp;
		}

		if (offset < 0) {
			offset += temp;
			i--;
		}

		int year = i;

		leap = CalendarData.leapMonth(i); // 闰哪个月
		boolean isLeap = false;

		for (i = 1; i < 13 && offset > 0; i++) {
			// 闰月
			if (leap > 0 && i == (leap + 1) && isLeap == false) {
				--i;
				isLeap = true;
				temp = CalendarData.leapDays(year);
			} else {
				temp = CalendarData.monthDays(year, i);
			}

			// 解除闰月
			if (isLeap == true && i == (leap + 1))
				isLeap = false;

			offset -= temp;
		}

		if (offset == 0 && leap > 0 && i == leap + 1)
			if (isLeap) {
				isLeap = false;
			} else {
				isLeap = true;
				--i;
			}

		if (offset < 0) {
			offset += temp;
			--i;
		}

		int month = i;
		int day = offset + 1;
		// System.out.println("(" + isLeap + ")" + year + "-" + month + "-" + day);

		LunarDate lunarDate = new LunarDate();
		lunarDate.year = year;
		lunarDate.isLeap = isLeap;
		lunarDate.month = month;
		lunarDate.day = day;
		return lunarDate;
	}

	public static void main(String[] args) {
		LunarDate lunarDate = convertDate2LunarDate(new Date());
		System.out.println(lunarDate);
		System.out.println(lunarDate.toFullString());
		System.out.println(LunarDate.toString(12, 17));
	}
}
